package org.example.pet.task;

import lombok.extern.slf4j.Slf4j;
import org.example.pet.mapper.AdoptionApplicationMapper;
import org.example.pet.pojo.Statistic;
import org.example.pet.service.StatisticService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Slf4j
@Component
public class StatisticScheduleTask {
    
    @Autowired
    private AdoptionApplicationMapper adoptionApplicationMapper;
    @Autowired
    private StatisticService statisticService;

    // 日期格式化器
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    /**
     * 每日凌晨1点统计昨日数据：
     * cron表达式：秒 分 时 日 月 周 年（年可选）
     * 0 0 1 * * ? ：每日凌晨1点执行
     */
    @Scheduled(cron = "0 0 1 * * ?")
//    @Scheduled(fixedRate = 5000)  // 5s一次，测试用
    public void statAdoptData() {
        // 计算昨日日期
        LocalDate yesterday = LocalDate.now().minusDays(1);
        String yesterdayStr = yesterday.format(DATE_FORMATTER);
        log.info("开始统计{}的领养数据", yesterdayStr);

        try {
            // 统计昨日领养成功总数
            Integer adoptSuccessCount = adoptionApplicationMapper.countByDateAndStatus(yesterdayStr);
            log.info("昨日领养成功总数：{}", adoptSuccessCount);

            // 将统计结果写入统计表
            Statistic statistic = new Statistic();
            statistic.setStatDate(yesterday);
            statistic.setCreateTime(LocalDateTime.now());
            statistic.setUpdateTime(LocalDateTime.now());
            statistic.setAdoptSuccessCount(adoptSuccessCount);
            statisticService.save(statistic);
        } catch (Exception e) {
            log.error("{}领养数据统计失败", yesterdayStr, e);
        }
    }
}
